package cn.edu.zafu.bigdata.x.zhouyuyan.work10;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    private static final String server_address = "192.168.16.1";
    private static final int port = 9876;
    private static final String request_message = "请求时间";

    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket();
            InetAddress serverAddress = InetAddress.getByName(server_address);
            byte[] requestData = request_message.getBytes();
            DatagramPacket requestPacket = new DatagramPacket(requestData,requestData.length,serverAddress,port);

            socket.send(requestPacket);
            System.out.println("已发送时间请求到：" + server_address + ":"+ port);

            byte[] buffer = new byte[1024];
            DatagramPacket responsePacket = new DatagramPacket(buffer,buffer.length);
            socket.receive(responsePacket);

            String timeString = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println("收到服务器时间响应：" + timeString);

            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
